<template>
  <div class="main">
    <div class="content">
      <div class="head">
        <div class="input">
          <span>培训名称：</span>
          <el-input v-model="queryData.train_name" placeholder="请输入" />
        </div>
        <div class="input">
        <span>培训状态：</span>
        <el-select clearable v-model="queryData.submit_status" placeholder="请选择">
          <el-option label="未提交" :value="1">未提交</el-option>
          <el-option label="已提交" :value="2">已提交</el-option>
        </el-select>
      </div>
        <el-button type="primary" class="btn" @click="search">查询</el-button>
        <el-button type="primary" class="btn" @click="reset">重置</el-button>
        <el-button type="primary" class="btn" @click="add">新增</el-button>
      </div>
      <el-table
        ref="dataForm"
        :data="tableData"
        border
        v-loading="isTableLoading"
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        style="width: 100%"
        :max-height="tableHeight"
      >
        <el-table-column fixed type="index" align="center" label="序号" width="50" />
        <el-table-column
          fixed
          prop="train_name"
          align="center"
          show-overflow-tooltip
          label="培训名称"
          min-width="140"
        />
        <el-table-column prop="appoint_staff_name" align="center" label="组织人" min-width="160"></el-table-column>
        <el-table-column prop="address" align="center" label="培训地点" min-width="140"></el-table-column>
        <el-table-column prop="content" align="center" label="培训内容" min-width="120"></el-table-column>
        <el-table-column prop="teacher" align="center" label="授课老师" min-width="140"></el-table-column>
        <el-table-column prop="company_name" align="center" label="创建人" width="160"></el-table-column>
        <el-table-column prop="hours" align="center" label="学时" min-width="100"></el-table-column>
        <el-table-column prop="submit_status" align="center" label="状态" width="140">
          <template #default="scope">{{ scope.row.submit_status == 1 ? '未提交' : '已提交' }}</template>
        </el-table-column>
        <!-- <el-table-column prop="img_url" align="center" label="图片" width="100">
          <template #default="scope">
            <span class="look" @click="handleImg(scope.row)">查看</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="time" align="center" label="培训时间" min-width="160"></el-table-column>
        <el-table-column prop="textures" align="center" show-overflow-tooltip label="备注" min-width="160"></el-table-column>
        <el-table-column fixed="right" align="center" prop="action" label="操作" width="180">
          <template #default="scope">
            <div class="action">
              <span @click="edit(scope.row,2)">查看</span>
              <span v-if="scope.row.submit_status == 1" @click="edit(scope.row,1)">编辑</span>
              <span @click="delOk(scope.row)">删除</span>
              <!-- <span>档案管理</span> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="margin-top: 5px; text-align: right"
        @size-change="search"
        @current-change="getList"
        :current-page.sync="queryData.page"
        :page-size.sync="queryData.size"
        layout="total, prev, pager, next,sizes,jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <span>确定删除吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delOk">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="isDetail ? '查看培训' : (ruleForm.id ? '编辑培训' : '新增培训')"
      :visible.sync="isShowAdd"
      width="800px"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        :model="ruleForm"
        style="width: 100%"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        label-width="100px"
      >
        <el-row :gutter="20">
          <!-- <el-form-item label="所属企业" prop="testId">
          <el-select style="width: 100%" v-model="ruleForm.testId" placeholder="请选择">
            <el-option label="企业" :value="1">企业</el-option>
          </el-select>
        </el-form-item> -->
          <el-col :span="12">
            <el-form-item label="培训名称" prop="train_name">
              <el-input :disabled="isDetail" v-model="ruleForm.train_name" placeholder="请输入培训名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训地点" prop="address">
              <el-input :disabled="isDetail" v-model="ruleForm.address" placeholder="请输入培训地点"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织人" prop="appoint_staff_id">
              <el-select :disabled="isDetail" style="width: 100%" v-model="ruleForm.appoint_staff_id" placeholder="请选择">
                <el-option v-for="(item, index) in staffArr" :key="index" :label="item.username" :value="item.id">{{
                  item.username
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训时间" prop="time">
              <el-date-picker
               :disabled="isDetail"
                v-model="ruleForm.time"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="请选择培训时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授课老师" prop="teacher">
              <el-input :disabled="isDetail" v-model="ruleForm.teacher" placeholder="请输入授课老师"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学时" prop="hours">
              <el-input-number 
                :disabled="isDetail" 
                v-model="ruleForm.hours" 
                placeholder="请输入学时"
                :min="0"
                :precision="1"
                controls-position="right"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col> 
  
          <el-col :span="18">
            <el-form-item label="参与人员" prop="inner_staff_ids">
              <div class="staff-selector">
                <el-input
                  :disabled="isDetail"
                  :value="selectedStaffNames"
                  placeholder="请选择参与人员"
                  readonly
                  style="width: calc(100% - 80px)"
                />
                <el-button 
                  :disabled="isDetail"
                  type="primary" 
                  @click="openStaffSelector"
                  style="margin-left: 10px"
                >
                  选择
                </el-button>
              </div>
            </el-form-item>
          </el-col>
    

          
          <el-col :span="12">
            <el-form-item label="其他人员" prop="staff_names">
              <el-input :disabled="isDetail" v-model="ruleForm.staff_names" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="培训内容" prop="content">
              <el-input
               :disabled="isDetail"
                type="textarea"
                :autosize="{ minRows: 3 }"
                placeholder="请输入培训内容"
                v-model="ruleForm.content"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
               :disabled="isDetail"
                type="textarea"
                :autosize="{ minRows: 3 }"
                placeholder="请输入备注"
                v-model="ruleForm.remark"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="状态" prop="submit_status">
              <el-radio-group :disabled="isDetail" v-model="ruleForm.submit_status">
                <el-radio :label="1">未提交</el-radio>
                <el-radio :label="2">已提交</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="图片" prop="img_url" v-if="isDetail && ruleForm.img_urls.length">
              <div class="img-box">
                <el-image v-for="(item,index) in ruleForm.img_urls" :key="index" :src="item" :preview-src-list="ruleForm.img_urls" class="info-img" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose('ruleForm')">取 消</el-button>
        <el-button v-if="!isDetail" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 人员选择弹窗 -->
    <el-dialog
      title="选择参与人员"
      :visible.sync="staffSelectorVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="staff-selector-content">
        <!-- 筛选条件 -->
        <div class="filter-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="filter-item">
                <label>组织架构：</label>
                <el-select 
                  v-model="staffQuery.department_id" 
                  placeholder="请选择组织架构"
                  clearable
                  @change="getStaffListForSelector"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="dept in departmentList" 
                    :key="dept.id" 
                    :label="dept.name" 
                    :value="dept.id"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="filter-item">
                <label>工种：</label>
                <el-select 
                  v-model="staffQuery.job_id" 
                  placeholder="请选择工种" 
                  clearable
                  @change="getStaffListForSelector"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="job in jobList" 
                    :key="job.id" 
                    :label="job.name" 
                    :value="job.id"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="filter-item">
                <label>姓名：</label>
                <el-input 
                  v-model="staffQuery.username" 
                  placeholder="请输入姓名" 
                  @input="getStaffListForSelector"
                  clearable
                />
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 人员列表 -->
        <div class="staff-list-section">
          <div class="list-header">
            <el-checkbox 
              v-model="selectAll" 
              @change="handleSelectAll"
              :indeterminate="isIndeterminate"
            >
              全选
            </el-checkbox>
            <span class="selected-count">已选择 {{ tempSelectedStaffIds.length }} 人</span>
          </div>
          
          <el-table
            ref="staffTable"
            :data="staffListForSelector"
            border
            v-loading="staffListLoading"
            empty-text="暂无数据"
            style="width: 100%"
            max-height="400px"
            @selection-change="handleStaffSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="username" label="姓名" width="150" />
            <el-table-column prop="idcard" label="身份证号" width="300" />
            <el-table-column prop="mobile" label="联系方式" min-width="140" />
          </el-table>

          <el-pagination
            background
            style="margin-top: 15px; text-align: right"
            @size-change="handleStaffPageSizeChange"
            @current-change="handleStaffPageChange"
            :current-page.sync="staffQuery.page"
            :page-size.sync="staffQuery.size"
            layout="total, prev, pager, next, sizes"
            :total="staffTotal"
          />
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelStaffSelection">取消</el-button>
        <el-button type="primary" @click="confirmStaffSelection">确定</el-button>
      </span>
    </el-dialog>

    <el-image-viewer
      v-if="showImg"
      :on-close="
        () => {
          showImg = false;
        }
      "
      :url-list="imgList"
    />
  </div>
</template>

<script>
import { OfflinetrainingList, upload, OfflinetrainingSave, OfflinetrainingDelete, StaffAllStaffs,OfflinetrainingInfo } from '@/api/manage';
import { StaffGetOptions } from '@/api/manage';
import { StaffList } from '@/api/manage';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
export default {
  name: 'staff',
  components: { ElImageViewer },
  data() {
    return {
      tableHeight: 500,
      name: '',
      list: [],
      level: 0,
      Node: {},
      isTableLoading: false,
      tableData: [],
      total: 0,
      queryData: {
        page: 1,
        size: 10,
        idcard: '',
        username: '',
        department_name: '',
      },
      dialogVisible: false,
      isShowAdd: false,
      ruleForm: {
        train_name: '',
        staffs: [],
        selectedArr: [],
        appoint_staff_id: '',
        staff_names:  '',
        time: '',
        address: '',
        content: '',
        teacher: '',
        hours: null,
        img_url: '',
        submit_status: 1,
        inner_staff_ids: [],
      },
      rules: {
        train_name: [{ required: true, message: '请输入培训名称', trigger: 'blur' }],
        appoint_staff_id: [{ required: true, message: '请选择组织人', trigger: 'change' }],
        time: [{ required: true, message: '请选择培训时间', trigger: 'change' }],
        address: [{ required: true, message: '请输入培训地点', trigger: 'blur' }],
        content: [{ required: true, message: '请输入培训内容', trigger: 'blur' }],
        teacher: [{ required: true, message: '请输入授课老师', trigger: 'blur' }],
        hours: [{ required: true, message: '请输入学时', trigger: 'blur' }],
        submit_status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        img_url: [{ required: true, message: '请上传图片', trigger: 'change' }],
        selectedArr: [{ required: true, message: '请选择培训人员', trigger: 'change' }],
      },
      eduList: [],
      jobList: [],
      levelList: [],
      showImg: false,
      imgList: [],
      staffArr: [],
      isDetail:false,
      selectedStaffNames: '',
      selectedStaffIds: [],
      staffSelectorVisible: false,
      staffQuery: {
        department_id: '',
        job_id: '',
        username: '',
        page: 1,
        size: 10,
      },
      departmentList: [],
      staffListForSelector: [],
      selectAll: false,
      isIndeterminate: true,
      tempSelectedStaffIds: [],
      staffListLoading: false,
      staffTotal: 0,
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 260;
    });
    this.getList();
    this.getStaffList();
    this.getStaffOptions();
  },
  methods: {
    search() {
      this.queryData.page = 1;
      this.getList();
    },
    reset() {
      this.queryData.train_name = '';
      this.queryData.submit_status = '';
      this.search();
    },
    down() {},
    add() {
      this.isShowAdd = true;
      this.ruleForm = {
        staff_names:  '',
        train_name: '',
        staffs: [],
        selectedArr: [],
        appoint_staff_id: '',
        time: '',
        address: '',
        content: '',
        teacher: '',
        hours: null,
        img_url: '',
        submit_status: 1,
        inner_staff_ids: [],
      };
      this.selectedStaffNames = '';
      this.isDetail = false;
      this.$refs['ruleForm'].resetFields();
    },
    edit(item,type) {
        OfflinetrainingInfo({
            id: item.id
        }).then((res) => { 
            this.ruleForm = res.data.model;
            this.$set(this.ruleForm, 'inner_staff_ids', res.data.model.inner_staff_ids.map((item) => Number(item)));
            
            // 更新选中人员的显示名称
            const selectedStaff = this.staffArr.filter(staff => 
              this.ruleForm.inner_staff_ids.includes(staff.id)
            );
            this.selectedStaffNames = selectedStaff.map(staff => staff.username).join(', ');
            
            this.isShowAdd = true;
            this.isDetail = type == 2 ? true : false;
        });
    },
    del(item) {
      this.dialogVisible = true;
      this.item = item;
    },
    delOk(item) {
      this.$confirm('确定删除该培训?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        OfflinetrainingDelete({
          id: item.id,
        }).then((res) => {
          this.$message.success('删除成功');
          this.dialogVisible = false;
          this.getList();
          this.item = null;
        });
      });
    },
    handleImg(item) {
      this.imgList = [item.img_url];
      this.showImg = true;
    },
    handleClose() {
      this.isShowAdd = false;
      if ( !this.isDetail ) {
        this.ruleForm = {
          train_name: '',
          staffs: [],
          selectedArr: [],
          appoint_staff_id: '',
          staff_names: '',
          time: '',
          address: '',
          content: '',
          teacher: '',
          hours: null,
          img_url: '',
          submit_status: 1,
          inner_staff_ids: [],
        };
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          OfflinetrainingSave(this.ruleForm).then((res) => {
            this.$message.success(this.ruleForm.id ? '修改成功' : '添加成功');
            this.getList();
            this.$refs[formName].resetFields();
            this.isShowAdd = false;
          });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    },
    handleAvatarSuccess(e) {
      let obj = new FormData();
      obj.append('file', e.file);
      upload(obj).then((res) => {
        this.ruleForm.img_url = res.data.url;
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    getList() {
      this.isTableLoading = true;
      OfflinetrainingList(this.queryData).then((res) => {
        this.isTableLoading = false;
        this.tableData = res.data.list;
        this.total = res.data.total;
      });
    },
    getStaffList() {
      StaffAllStaffs().then((res) => {
        this.staffArr = res.data.list;
      });
    },
    handleClear() {
      this.queryData.department_name = '';
      this.queryData.department_id = '';
      this.search();
    },
    openStaffSelector() {
      this.staffSelectorVisible = true;
      this.tempSelectedStaffIds = [...this.ruleForm.inner_staff_ids] || [];
      this.getStaffListForSelector();
    },
    getStaffListForSelector() {
      this.staffListLoading = true;
      const params = {
        page: this.staffQuery.page,
        size: this.staffQuery.size,
        department_id: this.staffQuery.department_id,
        job_id: this.staffQuery.job_id,
        username: this.staffQuery.username,
      };
      
      StaffList(params).then((res) => {
        this.staffListLoading = false;
        this.staffListForSelector = res.data.list || [];
        this.staffTotal = res.data.total || 0;
        
        // 设置已选中的人员
        this.$nextTick(() => {
          this.staffListForSelector.forEach(row => {
            if (this.tempSelectedStaffIds.includes(row.id)) {
              this.$refs.staffTable.toggleRowSelection(row, true);
            }
          });
        });
      }).catch(() => {
        this.staffListLoading = false;
      });
    },
    getStaffOptions() {
      StaffGetOptions().then((res) => {
        const data = res.data;
        // 处理组织架构数据
        this.departmentList = this.flattenOptions(data.departments || []);
        // 处理工种数据（使用jobs字段）
        this.jobList = this.flattenOptions(data.jobs || []);
      }).catch((error) => {
        console.error('获取选项数据失败:', error);
      });
    },
    flattenOptions(tree) {
      let result = [];
      tree.forEach(item => {
        result.push({
          id: item.id,
          value: item.value,
          label: item.label,
          name: item.name,
          department_name: item.name, // 兼容组织架构字段
          para_name: item.name // 兼容工种字段
        });
        if (item.children && item.children.length > 0) {
          result = result.concat(this.flattenOptions(item.children));
        }
      });
      return result;
    },
    handleStaffSelectionChange(selection) {
      this.tempSelectedStaffIds = selection.map(item => item.id);
      this.selectAll = selection.length === this.staffListForSelector.length && this.staffListForSelector.length > 0;
      this.isIndeterminate = selection.length > 0 && selection.length < this.staffListForSelector.length;
    },
    handleSelectAll(value) {
      if (value) {
        this.staffListForSelector.forEach(row => {
          this.$refs.staffTable.toggleRowSelection(row, true);
        });
      } else {
        this.$refs.staffTable.clearSelection();
      }
    },
    handleStaffPageSizeChange(newSize) {
      this.staffQuery.size = newSize;
      this.staffQuery.page = 1;
      this.getStaffListForSelector();
    },
    handleStaffPageChange(newPage) {
      this.staffQuery.page = newPage;
      this.getStaffListForSelector();
    },
    cancelStaffSelection() {
      this.staffSelectorVisible = false;
      this.tempSelectedStaffIds = [];
      this.staffQuery = {
        department_id: '',
        job_id: '',
        username: '',
        page: 1,
        size: 10,
      };
    },
    confirmStaffSelection() {
      // 更新表单数据
      this.ruleForm.inner_staff_ids = [...this.tempSelectedStaffIds];
      
      // 更新显示的人员名称
      const selectedStaff = this.staffArr.filter(staff => 
        this.tempSelectedStaffIds.includes(staff.id)
      );
      this.selectedStaffNames = selectedStaff.map(staff => staff.username).join(', ');
      
      this.staffSelectorVisible = false;
    },
  },
};
</script>

<style scoped>
.main {
  width: 100%;
  height: calc(-100px + 100vh);
  background: #fff;
  /* display: flex;
  align-items: flex-start; */
  overflow: hidden;
  padding: 25px 20px;
  position: relative;
}
.content {
  width: 100%;
  min-height: 70vh;
}
.action {
  display: flex;
  align-items: center;
  justify-content: center;
}
.action span,
.look {
  color: #0256ff;
  font-size: 12px;
  cursor: pointer;
  margin: 0 8px;
}
.head {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 20px;
  padding-bottom: 0px;
}
.input {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 20px;
}
.input > span {
  font-size: 12px;
  flex-shrink: 0;
}
.btn {
  margin-bottom: 20px;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}
.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100%;
  display: block;
}
.prompt {
  font-size: 12px;
  color: red;
  margin-bottom: 5px;
}
.img-box{
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 10px;

}
.info-img{
  width: 100px;
  height: 100px;
}
.staff-selector {
  display: flex;
  align-items: center;
}
.staff-selector-content {
  padding: 20px;
}
.filter-section {
  margin-bottom: 20px;
}
.filter-item {
  margin-bottom: 15px;
}
.filter-item label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #606266;
  font-weight: normal;
}
.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.selected-count {
  font-size: 12px;
  color: #606266;
}
</style>
